import { Config, Inject, Provide } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { BizWorkerWorkDatesEntity } from '../entity/workDates';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';

/**
 * 工期表服务
 */
@Provide()
export class BizWorkerWorkDatesService extends BaseService {
  @Config('module.bizWorker')
  config;

  @Inject()
  ctx;

  @InjectEntityModel(BizWorkerWorkDatesEntity)
  bizWorkerWorkDatesEntity: Repository<BizWorkerWorkDatesEntity>;

  async page(
    query: any,
    option: any,
    connectionName?: any
  ): Promise<{
    list: any;
    pagination: { page: number; size: number; total: number };
  }> {
    const { page, size, sort, order } = query;
    const { fieldEq, keyWordLikeFields } = option;

    const find = this.bizWorkerWorkDatesEntity.createQueryBuilder();
    const whereStrs = [];
    fieldEq.forEach((key: any) => {
      const queryStr = query[key];
      if (queryStr !== undefined) {
        whereStrs.push(`${key} = '${queryStr}'`);
      }
    });
    keyWordLikeFields.forEach((key: any) => {
      const { keyWord } = query;
      keyWord !== undefined && whereStrs.push(`${key} like '%${keyWord}%'`);
    });
    find.where(whereStrs.join(' && '));
    order &&
      find.orderBy(order ? order : 'id', sort ? sort.toUpperCase() : 'DESC');

    // console.log(whereStrs, find.getQuery());

    const { list, pagination } = await this.entityRenderPage(find, {
      page,
      size,
    });

    return {
      list,
      pagination,
    };
  }
}
